import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/mixin/auto_hide_loading.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/custom_cupertino_alert_dialog.dart';

class BindFrameDialog extends StatefulWidget {
  const BindFrameDialog({super.key});

  @override
  State<BindFrameDialog> createState() => _BindFrameDialogState();
}

class _BindFrameDialogState extends State<BindFrameDialog>
    with AutoHideLoading {
  final controller = TextEditingController();
  BindFrameViewModel vm = BindFrameViewModel();

  @override
  Widget build(BuildContext context) {
    return CustomCupertinoAlertDialog(
      title: Text(
        AppLocalizationsWrapper.instance.unwrap(context).fillInInvitationCode,
        style: TextStyle(
            fontSize: 16,
            color: Color(0xff333333),
            fontWeight: FontWeight.bold),
      ),
      content: Column(
        children: [
          Text(
            AppLocalizationsWrapper.instance
                .unwrap(context)
                .bindFrameDialogTips,
            style: TextStyle(
              fontSize: 14,
              color: Color(0xff333333),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 8.5),
            height: 44,
            padding: EdgeInsets.symmetric(horizontal: 14),
            decoration: BoxDecoration(
                color: Color(0xffEAECEE),
                borderRadius: BorderRadius.circular(10.0)),
            child: Row(
              children: [
                Expanded(
                  flex: 1,
                  child: TextField(
                    maxLines: 1,
                    minLines: 1,
                    controller: controller,
                    style:
                        TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                    decoration: InputDecoration(
                      hintMaxLines: 1,
                      isDense: true,
                      border: InputBorder.none,
                      hintText: AppLocalizationsWrapper.instance
                          .unwrap(context)
                          .enterInvitationCode,
                      hintStyle: TextStyle(
                        color: Colors.grey,
                        fontSize: 16,
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 6),
                CupertinoButton(
                  padding: EdgeInsets.zero,
                  onPressed: () {
                    ARouter.instance.pagePush('/scan').then((args) {
                      if (args != null && args['result'] != null) {
                        print("/scan res -> ${args['result']}");
                        setState(() {
                          controller.text = args['result'];
                        });
                      }
                    });
                  },
                  child: Image.asset("images/icon_qrcode.png",
                      width: 27, height: 27),
                ),
              ],
            ),
          ),
          SizedBox(height: 29.5),
        ],
      ),
      actions: <Widget>[
        CupertinoButton(
          padding: EdgeInsets.zero,
          onPressed: () {
            if (!vm.actionEnable) {
              return;
            }
            Navigator.pop(context);
          },
          child: Text(
            AppLocalizationsWrapper.instance.unwrap(context).cancel,
            style: TextStyle(
                fontSize: 16,
                color: Color(0xff333333),
                fontWeight: FontWeight.bold),
          ),
        ),
        CupertinoButton (
          padding: EdgeInsets.zero,
          onPressed: () async {
            if (!vm.actionEnable) {
              return;
            }
            final res = await vm.bind(context, controller.text);
            if (res) {
              Navigator.pop(context);
            }
          },
          child: Text(
            AppLocalizationsWrapper.instance.unwrap(context).confirm,
            style: TextStyle(
                fontSize: 16,
                color: Color(0xff3F74EF),
                fontWeight: FontWeight.bold),
          ),
        ),
      ],
    );
  }
}

class BindFrameViewModel extends ChangeNotifier {
  bool actionEnable = true;

  Future<bool> bind(BuildContext context, String code) {
    FocusManager.instance.primaryFocus?.unfocus();
    actionEnable = false;
    notifyListeners();
    EasyLoading.show();
    return HttpManager.instance
        .doRequest("/api/bind", parameters: {"code": code}).then((e) async {
      if (e.isSuccess) {
        EasyLoading.showToast(appLocal().bindFrameSuccessToast);
        return true;
      } else {
        Fluttertoast.showToast(msg: e.msg ?? "");
        return false;
      }
    }).catchError((e) {
      Fluttertoast.showToast(
          msg: AppLocalizationsWrapper.instance.unwrap(context).netError);
      return false;
    }).whenComplete(() {
      actionEnable = true;
      EasyLoading.dismiss();
    });
  }
}
